<script setup lang="ts">
import { ElMessageBox, ElNotification } from "element-plus";
import {
  RefreshLeft,
  Search,
  Plus,
  Edit,
  Delete,
  Grid
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { colums as tableColums, jiejiaList } from "./testData";
import { dayRangeArray } from "@/utils/index";
const loading = ref(false);
const queryForm = reactive({
  data: {
    name: undefined,
    year: undefined
  }
});
const search = () => {
  let data = [];
  if (queryForm.data.name && !queryForm.data.year) {
    data = defaultTableData.data.filter(
      item => item.name.indexOf(queryForm.data.name) > -1
    );
  }
  if (queryForm.data.year && !queryForm.data.name) {
    data = defaultTableData.data.filter(
      item => parseInt(item.year) === parseInt(queryForm.data.year)
    );
  }
  if (queryForm.data.name && queryForm.data.year) {
    data = defaultTableData.data.filter(
      item =>
        parseInt(item.year) === parseInt(queryForm.data.year) &&
        item.name.indexOf(queryForm.data.name) > -1
    );
  }
  if (!queryForm.data.name && !queryForm.data.year) {
    data = defaultTableData.data;
  }
  tableData.data = data;
};
const dataDelRow = row => {
  let index = defaultTableData.data.findIndex(item => item.id === row.id);
  defaultTableData.data.splice(index, 1);
};
const resetQuery = () => {
  queryForm.data = {
    name: undefined,
    year: undefined
  };
  tableData.data = defaultTableData.data;
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleSizeChange = () => {};
const handleCurrentChange = async () => {};
const defaultTableData = reactive({
  data: [
    {
      id: "1",
      name: "春节",
      begin: "2024-02-06",
      end: "2024-02-19",
      len: 13,
      year: 2024
    }
  ]
});
const tableData = reactive({
  data: []
});
const status = ref("add");
const edit = row => {
  title.value = "编辑";
  addDialog.value = true;
  status.value = "edit";
  form.data = JSON.parse(JSON.stringify(row));
};
const form = reactive({
  data: {
    name: undefined,
    begin: undefined,
    end: undefined,
    year: undefined,
    len: undefined
  },
  rules: {
    name: [{ required: true, message: "请选择节假日名称", trigger: "change" }],
    begin: [{ required: true, message: "请选择开始日期", trigger: "change" }],
    end: [{ required: true, message: "请选择结束日期", trigger: "change" }],
    year: [{ required: true, message: "请输入所属年份", trigger: "blur" }],
    len: [
      { required: true, message: "请设置开始和结束日期", trigger: "change" }
    ]
  }
});
const del = row => {
  ElMessageBox.confirm("是否确认删除该节假日?", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    dataDelRow(row);
    search();
    ElNotification({
      title: "系统提示",
      message: "删除成功",
      type: "success"
    });
  });
};
const formRules = ref(null);
const addDialog = ref(false);
const title = ref("添加");

const add = () => {
  title.value = "添加";
  addDialog.value = true;
  status.value = "add";
};
const cancel = () => {
  form.data = {
    name: undefined,
    begin: undefined,
    end: undefined,
    year: undefined,
    len: undefined
  };
  setTimeout(() => {
    formRules.value.clearValidate();
    addDialog.value = false;
  }, 0);
};
const beginChange = e => {
  if (e && form.data.end) {
    let days = dayRangeArray(e, form.data.end);
    form.data.len = days.length;
  } else {
    form.data.len = undefined;
  }
};
const endChange = e => {
  if (e && form.data.begin) {
    let days = dayRangeArray(form.data.begin, e);
    form.data.len = days.length;
  } else {
    form.data.len = undefined;
  }
};
const submit = () => {
  formRules.value.validate(valid => {
    if (valid) {
      if (status.value === "add") {
        defaultTableData.data.push(JSON.parse(JSON.stringify(form.data)));
      } else {
        defaultTableData.data.forEach(item => {
          if (item.id === form.data.id) {
            Object.assign(item, JSON.parse(JSON.stringify(form.data)));
          }
        });
      }
      search();
      cancel();
    }
  });
};
const init = () => {
  tableData.data = defaultTableData.data;
};
const beforeClose = async d => {
  await cancel();
  d();
};
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);
const defaultColums = reactive({
  data: []
});
const colums = reactive({
  data: []
});
onMounted(() => {
  defaultColums.data = tableColums;
  colums.data = tableColums;
  init();
  checkedCities.value = colums.data.map(item => item.prop);
});
const queryShow = ref(true);
const getList = () => {
  search();
};

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-row v-if="queryShow">
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-input
              v-model="queryForm.data.name"
              placeholder="请输入节假日名称查询"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="queryForm.data.year"
              placeholder="请输入所属年份查询"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="w-full flex justify-between mb-[10px]">
        <div class="buttons flex align-center">
          <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
          <!--          <el-button-->
          <!--            type="success"-->
          <!--            :icon="Edit"-->
          <!--            :disabled="!(multipleSelection.length === 1)"-->
          <!--            @click="editSelect"-->
          <!--          >修改</el-button-->
          <!--          >-->
          <!--          <el-button-->
          <!--            type="danger"-->
          <!--            :icon="Delete"-->
          <!--            :disabled="!multipleSelection.length"-->
          <!--            @click="delSelect"-->
          <!--          >删除</el-button-->
          <!--          >-->
          <!--            <el-button type="warning" :icon="Download" @click="exportData"-->
          <!--              >导出</el-button-->
          <!--            >-->
        </div>
        <div class="settings">
          <el-button-group class="ml-4">
            <el-button
              type="primary"
              :icon="Search"
              @click="queryShow = !queryShow"
            />
            <el-button type="primary" :icon="RefreshLeft" @click="getList" />
            <el-popover placement="bottom" :width="200" trigger="click">
              <template #reference>
                <el-button type="primary" :icon="Grid" />
              </template>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div class="group-box w-full max-h-[240px] overflow-y-auto">
                <el-checkbox-group
                  v-model="checkedCities"
                  class="columns-show-group"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="item in defaultColums.data"
                    :key="item.prop"
                    :label="item.prop"
                    >{{ item.label }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </el-popover>
          </el-button-group>
        </div>
      </div>
      <div class="w-full">
        <el-table :data="tableData.data" border width="100%">
          <el-table-column
            v-for="item in colums.data"
            :key="item.id"
            :label="item.label"
            :prop="item.key"
            :width="item.width"
            :align="item.align"
          />
          <el-table-column :fixed="'right'" label="操作" align="center">
            <template #default="scope">
              <el-button text type="primary" @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button text type="primary" @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page w-full mt-[10px]">
        <el-pagination
          v-model:current-page="pageObj.data.currentPage"
          v-model:page-size="pageObj.data.pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageObj.data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="addDialog"
      :before-close="beforeClose"
      :title="title"
      width="40%"
    >
      <div class="w-full">
        <el-form
          ref="formRules"
          class="display-block"
          :model="form.data"
          label-width="120px"
          :rules="form.rules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="节假日名称" prop="name">
                <el-select v-model="form.data.name" placeholder="请选择">
                  <el-option
                    v-for="item in jiejiaList"
                    :key="item.id"
                    :value="item.name"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始日期" prop="begin">
                <el-date-picker
                  v-model="form.data.begin"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                  date-format="YYYY-MM-DD"
                  :size="'default'"
                  style="width: 100%"
                  @change="beginChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="end">
                <el-date-picker
                  v-model="form.data.end"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                  date-format="YYYY-MM-DD"
                  :size="'default'"
                  style="width: 100%"
                  @change="endChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属年份" prop="year">
                <el-input v-model="form.data.year" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="假期时长(天)" prop="len">
                <el-input
                  v-model="form.data.len"
                  disabled
                  placeholder="根据开始和结束日期自动计算"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .demo-tabs {
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;

      .el-tabs__content {
        flex: 1;

        .el-tab-pane {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
